<?php
/**
 * Created by PhpStorm.
 * User: 王松
 * Time: 2017/8/4 18:04
 */

namespace App\Project\Reserve\Behaviours;

use App\Models\Reservation\Reservation;
use App\Models\Reservation\Schedule as ScheduleModel;
use App\Project\Reserve\Exceptions\NoAuthToObtainPlanException;
use App\User;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Collection;

/**
 * Class Schedule
 * @package App\Project\Reserve\Behaviours
 */
class Schedule
{
    /**
     * @var \App\User
     */
    protected $user;

    /**
     * @var \App\Models\Reservation\Schedule
     */
    protected $schedule;

    /**
     * @var \App\User
     */
    protected $authUser;

    /**
     * Schedule constructor.
     * @param \App\User $authUser
     */
    public function __construct(User $authUser)
    {
        $this->authUser    = $authUser;
        $this->user        = \Auth::user();
        $this->schedule    = new ScheduleModel();
    }

    public function planOfMonth($time = null)
    {
        $time  = $time ? Carbon::parse($time) : Carbon::now();
        $start = $time->startOfMonth()->toDateString();
        $end   = $time->endOfMonth()->toDateString();

        return $this->plan([$start, $end]);
    }

    /**
     * 获取多人的排班计划
     */
    public function plans()
    {

    }

    /**
     * 获取排班计划
     * @param null $times
     * @return \Illuminate\Support\Collection|static
     */
    public function plan($times = null)
    {
        $this->schedule = $this->schedule->whereTimeBetween($times);

        $schedule = $this->planWithWhere(['doctor_id' => $this->user->id]);

        return $schedule->groupBy('time')->map(function (Collection $schedule) {
                return $schedule->keyBy('am');
            }
        );
    }

    public function planWithWhere($where)
    {
        $this->checkThePlanAuth();

        return $this->schedule->where($where)->get()->sortBy('time');
    }

    protected function checkThePlanAuth()
    {
        if (
            ($this->user->id != $this->authUser->id)
            && $this->authUser->isA('nurse')
            && ($this->user->hospital_id != $this->authUser->hospital_id)
        ) {
            throw new NoAuthToObtainPlanException();
        }
    }

    /**
     * @param \App\User $user
     * @return $this
     */
    public function setUser($user)
    {
        $this->user = $user;

        return $this;
    }

    /**
     * 调用不存在的方法时，去调用模型的方法, 并返回模型
     * @param $method
     * @param $arguments
     * @return \Illuminate\Database\Eloquent\Collection|Reservation|null
     */
    public function __call($method, $arguments)
    {
        return $this->schedule->$method(...$arguments);
    }
}